package com.ty.controller;

import com.google.common.collect.Lists;
import com.ty.model.AjaxResult;
import com.ty.utils.QuartzUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.Set;
import java.util.UUID;

/**
 * @Author Tommy
 * @Date 2023/10/25
 */
@RestController
@RequestMapping("/quartz")
@Slf4j
public class QuartzController {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private JobDetail myJobDetail;

    @RequestMapping("/print")
    public AjaxResult print() throws Exception {
        QuartzUtil.printInfo(scheduler);
        return AjaxResult.success("请查看Server控制台");
    }

    @RequestMapping("/remove")
    public AjaxResult remove() throws Exception {
        Set<TriggerKey> triggerKeys = scheduler.getTriggerKeys(GroupMatcher.anyTriggerGroup());
        System.out.println("Trigger数量：" + triggerKeys.size());
        triggerKeys.stream().forEach(k -> {
            System.out.println("Group: " + k.getGroup());
            System.out.println("Name: " + k.getName());
        });
        System.out.println();

        boolean flag = scheduler.unscheduleJobs(Lists.newArrayList(triggerKeys));
        return AjaxResult.success("移除所有Trigger: " + flag);
    }

    @RequestMapping("/add")
    public AjaxResult add() throws Exception {
        Date start = Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant());
        System.out.print("触发器开始时间：");
        System.out.println(start);

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("myJobTrigger")
                .forJob(myJobDetail)
                .usingJobData("singal", 1)
                .usingJobData("deviceId", UUID.randomUUID().toString())
                .usingJobData("指令Charge", "Charge11")
                //.startAt(start)
                .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
                .build();

        Date d = scheduler.scheduleJob(trigger);
        return AjaxResult.success("已添加Trigger：" + start, "初次执行时间：" + d);
    }
}
